package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sky.mapper.OrderMapper;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description
 * @author: ZXX-挚爱
 * @time: 2023/6/16 0:04
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private WorkSpaceService workSpaceService;


    /** @author ZXX-挚爱
     * @Description 营业额数据统计
     * @Dete 0:11 2023/6/16
     * @Param [begin, end]
     * @return com.sky.result.Result<com.sky.vo.TurnoverReportVO>
     **/

    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();

            map.put("status", Orders.COMPLETED);
            map.put("begin", beginTime);
            map.put("end", endTime);

            Double turnover=orderMapper.sumByMap(map);

            turnover=(turnover==null) ? 0.0 :turnover;
            turnoverList.add(turnover);
        }

        TurnoverReportVO turnoverReportVO = TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
        return turnoverReportVO;
    }

    /** @author ZXX-挚爱
     * @Description 用户统计
     * @Dete 0:49 2023/6/16
     * @Param [begin, end]
     * @return com.sky.result.Result<com.sky.vo.UserReportVO>
     **/

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> newUserList = new ArrayList<>();//用户新增数
        List<Integer> totalUserList = new ArrayList<>();//总用户数
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Integer newUser=orderMapper.getNewUserCount(beginTime,endTime);
            Integer totalUser=orderMapper.getTotalUserCount(endTime);
            newUserList.add(newUser);
            totalUserList.add(totalUser);

        }
        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
        return userReportVO;
    }


    /** @author ZXX-挚爱
     * @Description 订单统计
     * @Dete 19:53 2023/6/16
     * @Param [begin, end]
     * @return com.sky.result.Result<com.sky.vo.OrderReportVO>
     **/

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> orderCountList = new ArrayList<>();//每天订单总数集合
        List<Integer> validOrderCountList = new ArrayList<>();//每天有效订单数集合
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount=orderMapper.getOrderCount(beginTime,endTime,null);
            Integer validOrderCount=orderMapper.getOrderCount(beginTime,endTime,Orders.COMPLETED);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        //时间区间内的总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内的总有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        Double orderCompletionRate=0.0;
        if (totalOrderCount!=0){
            orderCompletionRate=validOrderCount.doubleValue()/totalOrderCount.doubleValue();
        }

        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return orderReportVO;
    }

    /** @author ZXX-挚爱
     * @Description 销量top10统计
     * @Dete 20:57 2023/6/16
     * @Param [begin, end]
     * @return com.sky.result.Result<com.sky.vo.SalesTop10ReportVO>
     **/

    @Override
    public SalesTop10ReportVO getOrderTop(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime,endTime);
        String nameList = StringUtils
                .join(
                        goodsSalesDTOList
                                .stream()
                                .map(GoodsSalesDTO::getName)
                                .collect(Collectors.toList()), ",");
        String numberList = StringUtils
                .join(
                        goodsSalesDTOList
                                .stream()
                                .map(GoodsSalesDTO::getNumber)
                                .collect(Collectors.toList()), ",");

        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();

        return salesTop10ReportVO;
    }

    /**
     * 导出运营数据报表
     */
    @Override
    public XSSFWorkbook exportData() throws IOException {
        // 1. 读取运营数据报表模板
        InputStream is = ClassLoader.getSystemResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook wb = new XSSFWorkbook(is);
        is.close();
        // 2. 调用工作台接口，查询对应的报表数据，写数据到Excel中
        LocalDate begin = LocalDate.now().plusDays(-30);
        LocalDate end = LocalDate.now().plusDays(-1);
        BusinessDataVO businessData = workSpaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN),
                LocalDateTime.of(end, LocalTime.MAX));

        // 2.1 获取表格
        XSSFSheet sheet1 = wb.getSheetAt(0);
        // 2.2 获取行
        XSSFRow row2 = sheet1.getRow(1); // 第2行
        XSSFRow row4 = sheet1.getRow(3); // 第4行
        XSSFRow row5 = sheet1.getRow(4); // 第5行
        // 2.3 获取单元格
        XSSFCell cell_2_2 = row2.getCell(1);// 第2行第2个单元格 (日期范围)
        XSSFCell cell_4_3 = row4.getCell(2);// 第4行第3个单元格 (营业额)
        XSSFCell cell_4_5 = row4.getCell(4);// 第4行第5个单元格 (订单完成率)
        XSSFCell cell_4_7 = row4.getCell(6);// 第4行第7个单元格 (新增用户数)
        XSSFCell cell_5_3 = row5.getCell(2);// 第5行第3个单元格 (有效订单)
        XSSFCell cell_5_5 = row5.getCell(4);// 第5行第5个单元格 (平均客单价)
        // 2.4 填充数据
        cell_2_2.setCellValue("时间：" + begin + "至" + end); // 日期范围
        cell_4_3.setCellValue(businessData.getTurnover());// 营业额
        cell_5_3.setCellValue(businessData.getValidOrderCount()); // 有效订单
        cell_4_5.setCellValue(businessData.getOrderCompletionRate()); // 订单完成率
        cell_4_7.setCellValue(businessData.getNewUsers());  // 新增用户数
        cell_5_5.setCellValue(businessData.getUnitPrice()); // 平均客单价

        // 填充明细数据
        for (int i = 0; i < 30; i++) {
            // 查询某天对应的运营数据
            BusinessDataVO data = workSpaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(begin, LocalTime.MAX));
            // 获取行
            XSSFRow row8 = sheet1.getRow(7 + i);
            // 获取单元格并填充数据
            row8.getCell(1).setCellValue(begin.toString()); // 填充日期
            row8.getCell(2).setCellValue(data.getTurnover()); // 填充营业额
            row8.getCell(3).setCellValue(data.getValidOrderCount()); // 填充有效订单
            row8.getCell(4).setCellValue(data.getOrderCompletionRate()); // 填充订单完成率
            row8.getCell(5).setCellValue(data.getUnitPrice()); // 填充平均客单价
            row8.getCell(6).setCellValue(data.getNewUsers()); // 填充新增用户数
            begin = begin.plusDays(1);
        }
        // 3. 将准备好数据的工作簿返回
        return wb;
    }
}
